using System;
using System.Collections.Generic;
using System.Globalization;
using JetBrains.Annotations;
using Newtonsoft.Json.Linq;

public static class JsonUtils
{
	public static string AddToJson(string json, string key, string value)
	{
		return ReplaceLastOccurrence(json, "}", ",\"" + key + "\":\"" + value + "\"}");
	}

	public static string AddToJson(string json, string key, int value)
	{
		return ReplaceLastOccurrence(json, "}", ",\"" + key + "\":" + value + "}");
	}

	public static string AddToJson(string json, string key, double value)
	{
		return ReplaceLastOccurrence(json, "}", ",\"" + key + "\":" + value.ToString(CultureInfo.CreateSpecificCulture("en-US")) + "}");
	}

	private static string ReplaceLastOccurrence(string json, string oldValue, string newValue)
	{
		int num = json.LastIndexOf(oldValue, StringComparison.Ordinal);
		if (num == -1)
		{
			return json;
		}
		return json.Remove(num, oldValue.Length).Insert(num, newValue);
	}

	[CanBeNull]
	internal static Dictionary<string, object> DeserializeAsDictionary(string json)
	{
		if (string.IsNullOrEmpty(json))
		{
			return new Dictionary<string, object>();
		}
		return JObjectToDictionary(JObject.Parse(json));
	}

	[CanBeNull]
	private static Dictionary<string, object> JObjectToDictionary(JObject jObject)
	{
		Dictionary<string, object> dictionary = jObject.ToObject<Dictionary<string, object>>();
		if (dictionary == null)
		{
			return null;
		}
		Dictionary<string, object> dictionary2 = new Dictionary<string, object>(dictionary);
		foreach (KeyValuePair<string, object> item in dictionary)
		{
			if (item.Value is JObject jObject2)
			{
				dictionary2[item.Key] = JObjectToDictionary(jObject2);
			}
			else
			{
				dictionary2[item.Key] = item.Value;
			}
		}
		return dictionary2;
	}
}
